<template>
  <a-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    switchFullscreen
    @cancel="handleCancel"
    :confirmLoading="confirmLoading"
    v-drag
  >
    <div>
      <a-row style="margin-bottom: 14px">
        <a-col :span="24">
          <a-button v-if="dataForm.id" type="primary" @click="handleExportXls($t('调拨单详情'))" v-has="'BisGoodsTransferController:export'">{{
            $t('导出')
          }}</a-button>
          <a-button v-if="state == 1 || state == 2 || state == 3" type="primary" @click="printReport" style="margin-left: 8px" v-has="'BisGoodsTransferController:print'">{{
            $t('打印')
          }}</a-button>
        </a-col>
      </a-row>
      <div>
        <a-row :gutter="10" style="margin-bottom: 14px">
          <a-col :span="6" style="display: flex; align-items: center">
            <span style="white-space: nowrap; padding-right: 4px">{{ $t('调出门店') }}:</span>
            <a-select
              v-if="state != 1 && state != 2 && state != 3"
              :placeholder="$t('请选择')"
              :disabled="tenantid != ''"
              v-model="dataForm.outTenantId"
              style="width: calc(100% - 5em - 4px)"
              @change="changeTenant(1)"
            >
              <a-select-option v-for="(item, i) in tenantList" :key="i" :value="item.tenantId">{{
                item.code + item.name
              }}</a-select-option>
            </a-select>
            <span v-if="state == 1 || state == 2 || state == 3">{{
              dataForm.outTenantId ? dataForm.outTenantId_dictText : $t('总部')
            }}</span>
          </a-col>
          <a-col :span="6" style="display: flex; align-items: center">
            <span style="white-space: nowrap; padding-right: 4px">{{ $t('调出仓库') }}:</span>
            <a-tree-select
              v-if="state != 1 && state != 2 && state != 3"
              allowClear
              v-model="dataForm.outStore"
              style="width: calc(100% - 5em - 4px)"
              :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="storeList"
              :placeholder="$t('请选择')"
              @change="changStore(true, 1)"
            />
            <span v-if="state == 1 || state == 2 || state == 3">{{ dataForm.outStore_dictText }}</span>
          </a-col>
          <a-col :span="6" style="display: flex; align-items: center">
            <span style="white-space: nowrap; padding-right: 4px">{{ $t('调入门店') }}:</span>
            <a-select
              v-if="state != 1 && state != 2 && state != 3"
              :placeholder="$t('请选择')"
              :disabled="tenantid != ''"
              v-model="dataForm.inTenantId"
              style="width: calc(100% - 5em - 4px)"
              @change="changeTenant(2)"
            >
              <a-select-option v-for="(item, i) in tenantList" :key="i" :value="item.tenantId">{{
                item.code + item.name
              }}</a-select-option>
            </a-select>
            <span v-if="state == 1 || state == 2 || state == 3">{{
              dataForm.inTenantId ? dataForm.inTenantId_dictText : $t('总部')
            }}</span>
          </a-col>
          <a-col :span="6" style="display: flex; align-items: center">
            <span style="white-space: nowrap; padding-right: 4px">{{ $t('调入仓库') }}:</span>
            <a-tree-select
              v-if="state != 1 && state != 2 && state != 3"
              allowClear
              v-model="dataForm.inStore"
              style="width: calc(100% - 5em - 4px)"
              :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="inStoreList"
              :placeholder="$t('请选择')"
              @change="changStore(true, 2)"
            />
            <span v-if="state == 1 || state == 2 || state == 3">{{ dataForm.inStore_dictText }}</span>
          </a-col>
        </a-row>
        <a-row :gutter="10">
          <a-col :span="6" style="display: flex; align-items: center" v-if="state != 1 && state != 2 && state != 3">
            <span style="white-space: nowrap; padding-right: 4px">{{ $t('商品') }}:</span>
            <a-auto-complete
              ref="goodsId"
              :disabled="!dataForm.outStore"
              v-model="keyword"
              show-search
              option-label-prop="key"
              style="width: 100%"
              :placeholder="$t('请输入商品编码/名称/条码')"
              :filter-option="false"
              :not-found-content="null"
              :dropdown-match-select-width="false"
              :dropdown-style="{ width: '420px' }"
              @select="handleGoodsChange"
            >
              <template #dataSource>
                <a-select-opt-group v-for="group in goodsData" :key="group.title">
                  <template #label>{{$t('商品信息')}}</template>
                  <a-select-option v-for="goods in group.addGoodsList" :key="goods.goodsId" :value="goods">
                    {{
                    goods.stock
                      ? (goods.goodsCode
                          ? goods.goodsCode + '(' + goods.goodsId_dictText + ')'
                          : goods.goodsId_dictText) +
                        '  [ ' +
                        goods.stock +
                        ' ]'
                      : goods.goodsCode
                      ? goods.goodsCode + '(' + goods.goodsId_dictText + ')'
                      : goods.goodsId_dictText
                  }}
                  </a-select-option>
                </a-select-opt-group>
              </template>
              <a-input-search @search="handleGoodsSearch" enter-button></a-input-search>
            </a-auto-complete>
          </a-col>
          <a-col :span="3" v-if="state != 1 && state != 2 && state != 3" style="display: flex; align-items: center">
            <span style="white-space: nowrap; padding-right: 4px">{{ $t('数量') }}:</span>
            <a-input-number :formatter="formatter" :parser="parser" ref="number" v-model="curGoods.number" style="width: 100%" @pressEnter="addGoods" />
          </a-col>
          <a-col :span="8" v-if="state != 1 && state != 2 && state != 3">
            <a-button type="primary" @click="addGoods">{{ $t('添加') }}</a-button>
            <a-button type="primary" @click="handleAddConditions" style="margin-left: 8px">{{ $t('按条件添加') }}</a-button>
          </a-col>
        </a-row>
        <div v-if="state != 1 && state != 2 && state != 3" style="margin: 10px; font-size: 14px; font-weight: bold">
          {{ $t('商品列表') }}:
        </div>
        <a-table
          :columns="columns"
          :dataSource="dataSource"
          size="middle"
          bordered
          class="j-table-force-nowrap"
          :pagination="false"
          style="padding-left: 11px"
        >
          <template slot="action" slot-scope="text, record">
            <a-icon type="close" @click="deleteGoods(text, record)" />
          </template>
          <template slot="number" slot-scope="text, record">
            <a-input-number :formatter="formatter" :parser="parser" v-model="record.number" @change="handleAmount(record)" :ref="'number' + record.sign" />
          </template>
          <template slot="totalAmount" slot-scope="text, record">
            <a-input-number :formatter="formatter" :parser="parser"
              v-model="record.totalAmount"
              @change="handleAmount(record)"
              :ref="'totalamount' + record.sign"
            />
          </template>
          <template slot="comment" slot-scope="text, record">
            <a-input :ref="'comment' + record.sign" v-model="record.comment"></a-input>
          </template>
        </a-table>
        <div style="margin-top: 20px; font-weight: bolder">
          {{ $t('总数量') }}:{{ parseFloat(totalNum).toFixed(0) }} &nbsp; {{ $t('总金额') }}:{{ parseFloat(totalAmo).toFixed(2) }}&nbsp; {{ $t('备注') }}:&nbsp;
          <a-input
            v-if="state != 1 && state != 2 && state != 3"
            style="width: 300px"
            v-model="dataForm.comment"
            :placeholder="$t('请输入备注')"
          />
          <span v-if="state == 1 || state == 2 || state == 3">{{ dataForm.comment }}</span>
        </div>
      </div>
      <add-conditions-modal ref="addCondModal" @ok="handleCond"></add-conditions-modal>
      <goods-print-modal ref="printModal"></goods-print-modal>
    </div>
    <template slot="footer">
      <a-button type="primary" :disabled="confirmLoading" v-if="state == 0" @click="handleOk(0)">{{
        $t('保存')
      }}</a-button>
      <a-button type="primary" :disabled="confirmLoading" v-if="state != 1 && state != 3" @click="handleOk(1)">{{
        $t('保存并审核')
      }}</a-button>
      <a-button type="primary" v-has="'SalesAllotList:reverse'" :disabled="confirmLoading" v-if="state == 3" @click="reverse">{{
        $t('反审')
      }}</a-button>
      <a-button @click="handleCancel">{{ $t('关闭') }}</a-button>
    </template>
  </a-modal>
</template>

<script>
import Vue from 'vue'
import { TENANT_ID } from '@/store/mutation-types'
import { getAction, httpAction, downFile } from '@/api/manage'
import { formatter, parser } from '@/api/comm'
import AddConditionsModal from './AddConditionsModal'
import GoodsPrintModal from './GoodsPrintModal'
let that, selectedIds
export default {
  name: 'SalesAllotListModal',
  components: { AddConditionsModal, GoodsPrintModal },
  data() {
    return {
      formatter,
      parser,
      title: '',
      width: 800,
      visible: false,
      confirmLoading: false,
      disableSubmit: false,
      dataForm: {},
      goodsData: [
        {
          addGoodsList: [],
        },
      ],
      dataSource: [],
      columns: [],
      columns1: [
        {
          title: '',
          dataIndex: 'action',
          align: 'center',
          width: 30,
          customCell: function (column) {
            return {
              style: {
                textAlign: 'center',
                color: '#1890ff',
                fontSize: '16px',
                height: '32px',
                lineHeight: '32px',
                fontWeight: 'bold',
                cursor: 'pointer',
              },
            }
          },
          scopedSlots: { customRender: 'action' },
        },
        {
          title: this.$t('序号'),
          dataIndex: '',
          key: 'rowIndex',
          align: 'center',
          width: 70,
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: this.$t('商品编码'),
          dataIndex: 'goodsCode',
          align: 'center',
          width: 90,
        },
        {
          title: this.$t('商品名称'),
          dataIndex: 'goodsId_dictText',
          align: 'center',
          width: 360,
        },
        {
          title: this.$t('单位'),
          key: 'unit_dictText',
          dataIndex: 'unit_dictText',
          align: 'center',
        },
        {
          title: this.$t('规格'),
          key: 'standard',
          dataIndex: 'standard',
          align: 'center',
        },
        {
          title: this.$t('成本'),
          key: 'unitPrice',
          dataIndex: 'unitPrice',
          customRender: (t, r) => {
            return t.toFixed(2)
          },
          customHeaderCell: function (column) {
            return {
              style: {
                textAlign: 'center',
              },
            }
          },
          scopedSlots: { customRender: 'unitPrice' },
        },
        {
          title: this.$t('调拨数量'),
          key: 'number',
          dataIndex: 'number',
          align: 'center',
          width: '100px',
          scopedSlots: { customRender: 'number' },
        },
        {
          title: this.$t('总金额'),
          key: 'totalAmount',
          dataIndex: 'totalAmount',
          align: 'center',
          customRender: (t, r) => {
            return t.toFixed(2)
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          /* scopedSlots: { customRender: 'totalAmount' }, */
        },
        {
          title: this.$t('备注'),
          key: 'comment',
          dataIndex: 'comment',
          align: 'center',
          scopedSlots: { customRender: 'comment' },
        },
      ],
      columns2: [
        {
          title: this.$t('序号'),
          dataIndex: '',
          key: 'rowIndex',
          align: 'center',
          width: 100,
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: this.$t('商品编码'),
          dataIndex: 'goodsCode',
          align: 'center',
          width: 90,
        },
        {
          title: this.$t('商品名称'),
          dataIndex: 'goodsId_dictText',
          align: 'center',
          width: 250,
        },
        {
          title: this.$t('单位'),
          key: 'unit_dictText',
          dataIndex: 'unit_dictText',
          align: 'center',
        },
        {
          title: this.$t('规格'),
          key: 'standard',
          dataIndex: 'standard',
          align: 'center',
        },
        {
          title: this.$t('成本'),
          key: 'unitPrice',
          dataIndex: 'unitPrice',
          align: 'center',
          customRender: (t, r) => {
            return t.toFixed(2)
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('调拨数量'),
          key: 'number',
          dataIndex: 'number',
          align: 'center',
          customRender: (t, r) => {
            return t.toFixed(0)
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('总金额'),
          key: 'totalAmount',
          dataIndex: 'totalAmount',
          align: 'center',
          customRender: (t, r) => {
            return t.toFixed(2)
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('业务前库存'),
          key: 'beforeNum',
          dataIndex: 'beforeNum',
          align: 'center',
          customRender: (t, r) => {
            return t.toFixed(0)
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('业务后库存'),
          key: 'afterNum',
          dataIndex: 'afterNum',
          align: 'center',
          customRender: (t, r) => {
            return t.toFixed(0)
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('备注'),
          key: 'comment',
          dataIndex: 'comment',
          align: 'center',
        },
      ],
      url: {
        add: '/goods/bisGoodsTransfer/add',
        edit: '/goods/bisGoodsTransfer/edit',
        exportXlsUrl: '/goods/bisGoodsTransfer/detailExportXls',
      },
      totalNum: 0,
      totalAmo: 0,
      state: 0,
      curGoods: {},
      keyword: '',
      tenantList: [],
      storeList: [],
      inStoreList: [],
      tenantid: Vue.ls.get(TENANT_ID),
    }
  },
  created() {
    that = this
  },
  methods: {
    handleAddConditions() {
      if (!that.dataForm.outStore) {
        that.$message.warning(that.$t('请选择仓库'))
        return
      }
      that.$refs.addCondModal.edit()
    },
    handleCond(val) {
      if (val) {
        let querydata = {}
        querydata.parentKindId = val
        querydata.pageSize = 9999
        querydata.storeId = that.dataForm.outStore
        let dataSourceTwo = []
        getAction('/goods/bisGoodsStock/list', querydata).then((res) => {
          if (res.success) {
            res.result.records.forEach((col) => {
              let aa = {
                goodsId: col.goodsId,
                goodsCode: col.goodsCode,
                goodsId_dictText: col.goodsId_dictText,
                number: '',
                unitPrice: col.cost,
                totalAmount: 0,
                supplier_dictText: col.supplierId_dictText,
                supplier: col.supplierId,
                unit_dictText: col.unit_dictText,
                standard: col.standard,
                comment: '',
              }
              dataSourceTwo.push(aa)
            })
            dataSourceTwo.forEach((dst) => {
              let x = that.dataSource.findIndex((ds) => {
                return ds.goodsId == dst.goodsId
              })
              if (x == -1) {
                that.dataSource.push(dst)
              }
            })
            that.totalNum = 0
            that.totalAmo = 0
            that.dataSource.forEach((d, i) => {
              d.sign = i
              that.totalNum = (d.number?parseFloat(d.number):0) + parseFloat(that.totalNum)
              that.totalAmo = (parseFloat(d.totalAmount) + parseFloat(that.totalAmo))
            })
          }
        })
      }
    },
    add(obj) {
      selectedIds = []
      let dtl = {}
      if (!that.tenantid) {
        dtl = {
          outTenantId: 0,
          inTenantId: 0,
        }
      } else {
        dtl = {
          outTenantId: that.tenantid,
          inTenantId: that.tenantid,
        }
      }
      if(obj){
        if(obj.storeId){
          dtl.outStore = obj.storeId
        }
        if(obj.selectedIds){
          selectedIds = obj.selectedIds
        }
      }      
      that.edit(dtl)
    },
    edit(record, state) {
      that.visible = true
      that.storeList = []
      that.inStoreList = []
      that.confirmLoading = false
      that.keyword = ''
      that.dataSource = []
      that.curGoods = {}
      that.dataForm = {}
      that.totalAmo = 0
      that.totalNum = 0
      that.goodsData = []
      that.goodsData.push({ addGoodsList: [] })
      if (state == undefined) {
        that.state = 0
        that.columns = that.columns1
      } else {
        that.state = state
        that.columns = that.columns2
      }
      if(!record.id&&selectedIds.length>0){
        let dataSourceTwo = []
        getAction('/goods/bisGoodsStock/list', {goodsId: selectedIds.join(','), storeId: record.store, pageSize: 1000}).then((res) => {
          console.log(res)
          if(res.success){
            res.result.records.forEach((col) => {
              let aa = {
                goodsId: col.goodsId,
                goodsCode: col.goodsCode,
                goodsId_dictText: col.goodsId_dictText,
                number: '',
                unitPrice: col.cost,
                stock: col.stock,
                totalAmount: 0,
                unit_dictText: col.unit_dictText,
                standard: col.standard,
                comment: '',
              }
              dataSourceTwo.push(aa)
            })
            dataSourceTwo.forEach((dst) => {
              let x = that.dataSource.findIndex((ds) => {
                return ds.goodsId == dst.goodsId
              })
              if (x == -1) {
                that.dataSource.push(dst)
              }
            })
            that.dataSource.forEach((d, i) => {
              d.sign = i
            })
          }
        })
      }
      that.dataForm = Object.assign({}, record)
      that.tenantList = []
      that.getTenant()
      if (record) {
        getAction('/goods/bisGoodsTransfer/queryBisGoodsTransferDetailsByMainId', { id: record.id }).then((res) => {
          if (res.success) {
            that.dataSource = res.result
            that.dataSource.forEach((col) => {
              that.totalNum += col.number
              that.totalAmo += col.totalAmount
            })
          }
        })
      }
    },
    getTenant() {
      getAction('/shop/bisShop/list', { pageSize: 100 }).then((res) => {
        if (res.success) {
          that.tenantList = res.result.records
          if (!that.tenantid && !that.tenantList.find(item=>item.tenantId === 0)) {
            that.tenantList.unshift({ name: that.$t('总部'), tenantId: 0, code: '' })
          }
          that.getStore()
          that.getInStore()
        }
      })
    },
    changeTenant(arg) {
      if (arg == 1) {
        delete that.dataForm.outStore
        that.keyword = []
        that.getStore()
      }
      if (arg == 2) {
        delete that.dataForm.inStore
        that.getInStore()
      }
    },
    getStore() {
      let storeList = []
      let param = {}
      param.pageNo = 1
      param.pageSize = 9999
      param.column = 'id'
      param.order = 'DESC'
      param.tenantId = that.dataForm.outTenantId
      getAction('/goods/bisGoodsStore/rootList', param).then((res) => {
        if (res.success) {
          storeList = res.result.records
          if (storeList.length > 0) {
            storeList.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.id = '' + col.id
              col.pid = '' + col.pid
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChildStore(col, 'storeList')
              }
            })
            that.storeList = that.getDataByResult(storeList)
          }else {
            that.storeList = []
          }
        }else {
          that.storeList = []
        }
      })
    },
    getInStore() {
      let storeList = []
      let param = {}
      param.pageNo = 1
      param.pageSize = 9999
      param.column = 'id'
      param.order = 'DESC'
      param.tenantId = that.dataForm.inTenantId
      getAction('/goods/bisGoodsStore/rootList', param).then((res) => {
        if (res.success) {
          storeList = res.result.records
          if (storeList.length > 0) {
            storeList.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.id = '' + col.id
              col.pid = '' + col.pid
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChildStore(col, 'inStoreList')
              }
            })
            that.inStoreList = that.getDataByResult(storeList)
          }else {
            that.inStoreList = []
          }
        }else {
          that.inStoreList = []
        }
      })
    },
    getHasChildStore(store, key) {
      let that = this
      let query = {}
      query.pageNo = 1
      query.pageSize = 9999
      query.pid = store.id
      getAction('/goods/bisGoodsStore/rootList', query).then((res) => {
        if (res.success) {
          if (res.result.records.length > 0) {
            res.result.records.forEach((col) => {
              col.key = '' + col.id
              col.value = '' + col.id
              col.title = '' + col.name
              col.pid = '' + col.pid
              col.id = '' + col.id
              col.hasChild = '' + col.hasChild
              if (col.hasChild != '0') {
                that.getHasChildStore(col)
              }
            })
            store.children = that.getDataByResult(res.result.records)
            that[key] = [...that[key]]
          }
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    getDataByResult(result) {
      return result.map((item) => {
        return item
      })
    },
    addGoods() {
      if (!that.dataForm.outStore) {
        that.$message.warning(that.$t('请选择仓库'))
        return
      }
      if (!that.curGoods.goodsId) {
        that.$message.warning(that.$t('请选择商品'))
        that.$refs.goodsId.focus()
        return
      }
      let obj = {
        goodsId: that.curGoods.goodsId,
        goodsCode: that.curGoods.goodsCode,
        goodsId_dictText: that.curGoods.goodsId_dictText,
        number: that.curGoods.number,
        unit_dictText: that.curGoods.unit_dictText,
        standard: that.curGoods.standard,
        unitPrice: that.curGoods.cost,
        totalAmount:
          that.curGoods.number && that.curGoods.cost
            ? (parseInt(that.curGoods.number) * parseFloat(that.curGoods.cost))
            : '0.00',
        comment: '',
      }
      let x = that.dataSource.findIndex((d) => {
        return d.goodsId == obj.goodsId
      })
      if (x == -1) {
        that.dataSource.unshift(obj)
        that.totalAmo = 0
        that.totalNum = 0
        that.dataSource.forEach((d, i) => {
          d.sign = i
          that.totalNum = (d.number?parseFloat(d.number):0) + parseFloat(that.totalNum)
          that.totalAmo = (parseFloat(d.totalAmount) + parseFloat(that.totalAmo))
        })
      } else {
        that.$message.warning(`${obj.goodsCode}${obj.goodsId_dictText}` + that.$t('商品已存在'))
      }
      that.$nextTick(() => {
        that.curGoods = {}
        that.keyword = ''
        that.goodsData=[]
        that.$refs.goodsId.focus()
      })
    },
    changStore(state, arg) {
      if (state && that.dataSource.length > 0 && arg == 1) {
        that.$confirm({
          title: that.$t('提示'),
          content: that.$t('切换仓库将清空商品列表，确定要切换吗？'),
          okText: this.$t("确定"),
          cancelText: this.$t("取消"),
          onOk() {
            that.dataSource = []
            return
          },
          onCancel() {},
        })
      }
      if (arg === 1) {
        that.totalNum = 0
        that.totalAmo = 0
        that.curGoods = {}
        that.keyword = ''
        that.goodsData = []
      }
      that.$nextTick(() => {
        if (arg === 2) {
          that.$refs.goodsId.focus()
        }
      })
    },
    handleGoodsSearch() {
      that.getGoodsList(that.keyword)
    },
    getGoodsList(value) {
      let querydata = {}
      that.addGoodsList = []
      querydata.pageNo = 1
      querydata.pageSize = 10
      querydata.goodsInfo = value
      querydata.storeId = that.dataForm.outStore
      that.goodsData = []
      getAction('/goods/bisGoodsStock/list', querydata).then((res) => {
        if (res.success) {
          if (res.result.total > 0) {
            let goodsList = res.result.records
            if (goodsList.length > 1) {
              that.goodsData.push({ addGoodsList: goodsList })
            } else {
              that.handleGoodsChange(goodsList[0])
            }
          }else{
            that.$message.warn(that.$t('未找到符合的商品'))
            that.keyword=''
          }
        }
      })
    },
    handleAmount(record) {
      if (record.number > record.stock || isNaN(record.number)) {
        that.$message.warning(that.$t('调拨数量应小于等于当前库存'))
        return
      }
      if (record.number != '' && record.unitPrice != '') {
        record.totalAmount = parseFloat(record.number) * parseFloat(record.unitPrice)
      } else {
        record.totalAmount = '0'
      }
      that.totalNum = 0
      that.totalAmo = 0
      that.dataSource.forEach((res) => {
        that.totalNum = (res.number != '' ? parseFloat(res.number) : 0) + parseFloat(that.totalNum)
        that.totalAmo = (res.totalAmount != '' ? parseFloat(res.totalAmount) : 0) + parseFloat(that.totalAmo)
      })
    },
    deleteGoods(a, b) {
      that.dataSource.forEach((col) => {
        if (col.goodsId == b.goodsId) {
          let index = that.dataSource.indexOf(col)
          that.dataSource.splice(index, 1)
        }
      })
    },
    handleOk(state) {
      let querydata = {}
      querydata = that.dataForm
      if (querydata.outStore == undefined) {
        that.$message.warning(that.$t('请先选择调出仓库'))
        that.confirmLoading = false
        return
      }
      if (querydata.inStore == undefined) {
        that.$message.warning(that.$t('请先选择调入仓库'))
        that.confirmLoading = false
        return
      }
      if (that.dataSource.length == 0) {
        that.$message.warning(that.$t('商品不能为空'))
        return
      }
      let arr = that.dataSource.filter((d) => {
        return d.number == '' || d.number == null || d.number == '0'
      })
      if (arr.length > 0) {
        if ((arr[0].number == '' || arr[0].number == null) && arr[0].number !== 0) {
          that.$message.warning('['+arr[0].goodsId_dictText+'] '+that.$t('调拨数量不能为空'))
          that.$refs['number' + arr[0].sign].focus()
          return
        }
        if (arr[0].number == '0') {
          that.$message.warning('['+arr[0].goodsId_dictText+'] '+that.$t('调拨数量不能为0'))
          that.$refs['number' + arr[0].sign].focus()
          return
        }
        return
      }
      that.confirmLoading = true
      querydata.bisGoodsTransferDetailsList = that.dataSource
      querydata.state = state
      let httpurl = ''
      let method = ''
      if (!that.dataForm.id) {
        httpurl += that.url.add
        method = 'post'
      } else {
        httpurl += that.url.edit
        method = 'put'
      }
      httpAction(httpurl, querydata, method).then((res) => {
        if (res.success) {
          that.close()
          that.$message.success(res.message)
        } else {
          that.confirmLoading = false
          that.$message.warning(res.message)
        }
      })
    },
    handleCancel() {
      that.close()
    },
    close() {
      selectedIds = []
      that.$emit('ok')
      that.visible = false
    },
    handleExportXls(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = that.$t('导出文件')
      }
      let param = {}
      param.orderId = that.dataForm.id
      console.log('导出参数', param)
      downFile(that.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          that.$message.warning(that.$t('文件下载失败'))
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    printReport() {
      that.$refs.printModal.show(that.dataForm, 3)
    },
    handleGoodsChange(value) {
      that.curGoods = JSON.parse(JSON.stringify(value))
      that.keyword = that.curGoods.goodsId_dictText
      that.$refs.number.focus()
    },
    reverse(){
      httpAction('/goods/bisGoodsTransfer/reverse', {id:that.dataForm.id}, 'put').then((res) => {
        if (res.success) {
          that.close()
          that.$message.success(res.message)
        } else {
          that.confirmLoading = false
          that.$message.warning(res.message)
        }
      })
    }
  },
}
</script>

<style scoped>
</style>